<?php
namespace juven\libs {
    \defined( '_JEXEC' ) or die( 'Restricted access' );

    /**
     * Description of formBase
     *
     * @author George Zeakis <zeageorge@gmail.com>
     */
    abstract class FormBase {

        const EVENT_on  = "event_on";

        protected $_className   = \NULL;
        protected $_childClass  = \NULL;
        protected $_controllerName  = \NULL;
        protected $_formFields  = \NULL;
        protected $_form_id     = \NULL; // the form id (token), will be stored in session
        protected $_dateCreated = \NULL; // date-time (timestamp) the form was created, will be stored in session
        protected $_ttl         = \NULL; // Time to live in seconds, will be stored in session 

        abstract protected function _init();
        public function __construct($controllerName) {
            $this->_className   = __CLASS__;
            $this->_childClass  = \get_called_class();
            $this->_controllerName  = $controllerName;
            $this->_dateCreated = \time();
            $this->_form_id     = "id_".$this->getNew_FormId();
            $this->_ttl         = juven::config()->Forms->TimeToLive;
            
            $dtp                = new \stdClass();
            $dtp->className     = $this->_className;
            $dtp->childClass    = $this->_childClass;
            juven::eventsManager()->publish(self::EVENT_on, $dtp);

            $this->_init();
        }
        
        protected function getNew_FormId($partsSeparator="-"){
            $random = \preg_replace_callback('/[xy]/', 
                    function ($matches){
                        return \dechex('x' == $matches[0] ? \mt_rand(0, 15) : (\mt_rand(0, 15) & 0x3 | 0x8));
                    }, "xxxxxxxxxxxxxxxx"
            );
            $random .= $partsSeparator.\time();
            return md5($random);
        }
        
        public function render($viewFile=\NULL){
            if ($viewFile===\NULL){
                $f = juven::config()->formsFolderPath.$this->_controllerName.\DIRECTORY_SEPARATOR.\substr($this->_childClass, \strrpos($this->_childClass,"\\")+1)."_view.php";
                if (\is_readable($f)){
                    include $f;
                    return \TRUE;
                }
            }
        }
    }
}
?>
